const query = require('../db/mysql');
const { success, error } = require('../model/model');
class ListController {
    getList = async (ctx) => {
        const { id, keyword, sortBy, sortType, pageIndex, PageSize } = ctx.query;
        let sql = `select * from juejin where 1=1 `;
        let sqlCount = `select count(id) as total from juejin where 1=1 `;
        if (id) {
            sql += `and id=${id} `;
            sqlCount += `and id=${id} `
        }
        if (keyword) {
            sql += `and title link "%${keyword}%" `;
            sqlCount += `and title link "%${keyword}" `;
        }
        if (sortBy && sortType) {
            sql += `order by ${sortBy} ${sortType}`
        }
        if (pageIndex && PageSize) {
            sql += `limit ${(pageIndex - 1) * pageSize},${pageSize}`
        }
        const data = await query(sql);
        const count = await query(sqlCount);
        ctx.body = success({
            data: data,
            total: count[0].total
        })
    }
    addList = async (ctx) => {
        const { title, names } = ctx.request.body;
        const sql = `insert into juejin(title,names,times) values("${title}","${names}","${Date.now()}")`;
        const data = await query(sql);
        if(data.affectedRows===1){
            ctx.body=success({
                id:data.insertId
            })
        }else{
            ctx.body=console.error(('编辑失败'));
        }
    }
    editList=async(ctx)=>{
        const {title,names,id}=ctx.request.body;
        const sql=`update blogs set title="${title}",names="${names}" where id="${id}"`;
        const data=await query(sql);
        if(data.affectedRows===1){
            ctx.body=success('编辑成功')
        }else{
            ctx.body=error('编辑失败')
        }
    }
    delList=async(ctx)=>{
        const {id}=ctx.params;
        const sql=`delete from juejin where id=${id}`;
        const data=await query(sql);
        if(data.affectedRows===1){
            ctx.body=success('删除成功')
        }else{
            ctx.body=error('删除成功')
        }
    }
}
module.exports = new ListController()
